package com.lcj.mis.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lcj.mis.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 热力图定时任务类
 */
@Slf4j
@Component
public class HeatMapCountTask {

    @Resource
    private OrderService orderService;

    @Value("${heatMap.layerid}")
    private String layerid;

    @Value("${heatMap.key}")
    private String key;

    @Value("${heatMap.table_id}")
    private String tableId;

    /**
     * 腾讯地图数据更新URL
     */
    private String dataUpdateUrl = "https://apis.map.qq.com/mydata/data/create";
    /**
     * 腾讯地图热力图图层发布URL
     */
    private String publishUrl = "https://apis.map.qq.com/data_layer/v1/publish";

    /**
     * 统计热点区域定时任务
     */
    @Scheduled(cron = "${heatMap.time_cron}")
    public void count() throws UnsupportedEncodingException {
        ArrayList<HashMap> map = orderService.searchOrderStartLocationIn30Days();

        double[][] data = new double[map.size()][3];
        for(int i = 0; i < map.size(); i++) {
            data[i][0] = (double)map.get(i).get("latitude");
            data[i][1] = (double)map.get(i).get("longitude");
            data[i][2] = (int)map.get(i).get("count");
        }
        JSONObject jsonData = new JSONObject();
        jsonData.put("key", key);//开发密钥（Key），注意使用的key必须有对指定表的写入权限
        jsonData.put("table_id", tableId);//数据表ID
        jsonData.put("action_type", 2);//操作类型：1追加数据[默认]，2全表覆盖
        jsonData.put("data", data);
        String result = HttpUtil.createPost(dataUpdateUrl)
                .header("content-type","application/json;charset=UTF-8")
                .body(jsonData.toString())
                .execute().body();
        JSONObject res = JSON.parseObject(result);
        if(res.getIntValue("status") == 0) {
            log.info("【热力图】{}条数据统计成功", map.size());
            Map param = new HashMap();
            param.put("layerid", layerid);
            param.put("key", key);
            JSONObject publishRes = JSONObject.parseObject(HttpUtil.createGet(publishUrl).form(param).execute().body());
            if(publishRes.getIntValue("status") == 0) {
                log.info("【热力图】发布成功", tableId);
            } else {
                log.error("【热力图】发布失败\n{}", publishRes);
            }

        } else {
            log.error("【热力图】数据导入失败:\n结果:\n{}", result);
        }
    }

}
